<?php

namespace api\modules\v1\controllers\soup;

use common\models\soup\Soup;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;

class SoupController extends OnAuthController
{
    protected $optional = ['create','update','add','random-one'];

    public $modelClass = Soup::class;


    /**
     * 添加内容
     * @return bool
     * @throws NotFoundHttpException
     */
    public function actionAdd()
    {
        $request = \Yii::$app->request;
        $data = $request->post();

        if(!$data['title']){
            throw  new NotFoundHttpException('请输入鸡汤内容！');
        }
        $data['status'] =   0;

        $model = new Soup();
        if($model->load($data,'') && $model->save()){
            return ['tips'=>'审核通过后，鸡汤会带上你的大名哦！'];
        } else {
            throw new NotFoundHttpException(json_encode($model->getErrors()));
        }
    }


    /**
     * 随机一个
     * @return array|\yii\db\ActiveRecord|null
     */
    public function actionRandomOne()
    {
        $type = \Yii::$app->request->get('type', 0);
        $random = Soup::find()->where(['type' => $type, 'status' => 1])->orderBy('RAND()')->limit(1)->one();

        if($random){
            $random->updateCounters(['hits'=>1]);
        }
        return ['title'=>$random->title,'author'=>$random->author];
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, [''])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
